package com.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.entity.Transaction;
import org.apache.ibatis.annotations.*;

import java.util.List;

@Mapper
public interface TransactionMapper extends BaseMapper<Transaction> {

    /**
     * 根据用户ID查询交易记录
     * @param userId 用户ID
     * @return 交易记录列表
     */
    @Select("SELECT * FROM transactions WHERE user_id = #{userId}")
    List<Transaction> selectByUserId(int userId);


    //根据userid查询交易记录 并且包含了分类名字的包装
    @Select("SELECT t.transaction_id, t.user_id, t.category_id, c.name as category_name, t.amount, t.date, t.description " +
            "FROM transactions t " +
            "JOIN categories c ON t.category_id = c.id " +
            "WHERE t.user_id = #{id}")
    @Results({
            @Result(property = "transactionId", column = "transaction_id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "categoryId", column = "category_id"),
            @Result(property = "categoryName", column = "category_name"),
            @Result(property = "amount", column = "amount"),
            @Result(property = "date", column = "date"),
            @Result(property = "description", column = "description")
    })
    List<Transaction> selectTransactionsWithCategoryNames(int userId);

    //修改账目的时候 通过账目的id查询当前账目的所有信息
    @Select("SELECT t.transaction_id, t.user_id, t.category_id, t.amount, t.date, t.description, c.name as category_name " +
            "FROM transactions t " +
            "LEFT JOIN categories c ON t.category_id = c.id " +
            "WHERE t.transaction_id = #{transactionId}")
    @Results({
            @Result(property = "transactionId", column = "transaction_id"),
            @Result(property = "userId", column = "user_id"),
            @Result(property = "categoryId", column = "category_id"),
            @Result(property = "amount", column = "amount"),
            @Result(property = "date", column = "date"),
            @Result(property = "description", column = "description"),
            @Result(property = "categoryName", column = "category_name")
    })
    Transaction getTransactionWithCategoryNameById(@Param("transactionId") int transactionId);


    //通过前端传过来的表单数据修改transaction表
    @Update("UPDATE transactions SET " +
            "user_id = #{userId}, " +
            "category_id = #{categoryId}, " +
            "amount = #{amount}, " +
            "date = #{date}, " +
            "description = #{description} " +
            "WHERE transaction_id = #{transactionId}")
    int updateTransaction(Transaction transaction);

    //接收传过来的transactionsId 删除对应的transactions
    @Delete("DELETE FROM transactions WHERE transaction_id = #{transactionId}")
    int deleteTransactionById(Long transactionId);

    @Select("SELECT * FROM transactions WHERE category_id = #{id}")
    List<Transaction> getTransactionsByCategory(long id);
}
